package com.gengral.bussiness.sys.auth;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gengral.bussiness.sys.user.entity.User;
import com.gengral.bussiness.sys.user.service.UserService;
import com.gengral.commons.annotation.SysLog;
import com.gengral.commons.constant.Constant;
import com.gengral.commons.exception.BusinessException;
import com.gengral.commons.msg.BaseResponse;
import com.gengral.commons.utils.ResponseMsgUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.security.auth.Subject;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sht
 * @date 2020-04-14
 */
@RestController
@CrossOrigin
@Api(value = "权限接口")
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private UserService userService;

    @ApiOperation(value = "登录接口",notes="")
    @ApiImplicitParam(name = "user", value = "user实体中的参数", required = true, dataType = "User")
    @PostMapping("/login")
    @SysLog(description = "登录接口")
    public BaseResponse user(@RequestBody User user) throws Exception {
        String userCode = user.getUserCode();
        String passWord = user.getPassWord();
        if(StringUtils.isEmpty(userCode) || StringUtils.isEmpty(passWord)){
            throw new BusinessException(Constant.SYS_WARN_MSG_ISNULL_USER);
        }
        //根据usercode查询账号
        QueryWrapper<User> query = new QueryWrapper<User>();
        query.eq("user_code",userCode).eq("del_flag",1);
        user = userService.getOne(query);
        if(null == user){
            throw new BusinessException(Constant.USER_IS_NULL);
        }
//        // 拿到当前用户(可能还是游客，没有登录)
//        Subject currentUser = SecurityUtils.getSubject();
//        // 如果这个用户没有登录,进行登录功能
//        if( !currentUser.isAuthenticated() ) {
//            try{
//                // 验证身份和登陆
//                UsernamePasswordToken token = new UsernamePasswordToken(userCode, passWord);
//                // String token = MD5Utils.encrypt( String.valueOf( System.currentTimeMillis() ) );
//                currentUser.login(token);
//            }catch (UnknownAccountException e) {
//                return ResponseMsgUtil.error("账号不存在!");
//            } catch (IncorrectCredentialsException e) {
//                return ResponseMsgUtil.error("用户名或者密码错误!");
//            } catch (LockedAccountException e) {
//                return ResponseMsgUtil.error("登录失败，该用户已被冻结!");
//            } catch (AuthenticationException e) {
//                return ResponseMsgUtil.error("未知错误!");
//            }
//        }
        return ResponseMsgUtil.success();
    }
}
